package com.smarttiger.zero.logic.impl;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.smarttiger.zero.admin.dao.SubscribeDao;
import com.smarttiger.zero.admin.entity.*;
import com.smarttiger.zero.admin.entity.ArgsModel;
import com.smarttiger.zero.admin.entity.LogsModel;
import com.smarttiger.zero.admin.entity.SubscribeModel;
import com.smarttiger.zero.admin.service.LogsService;
import com.smarttiger.zero.logic.BaseLogic;
import com.smarttiger.zero.logic.InterfaceContext;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * Created by zhouzhengwei on 2021/10/25.
 */
@Component
public class TaskSendMessageLogic extends BaseLogic {

    @Autowired
    SubscribeDao subscribeDao;

    @Autowired
    LogsService logsService;


    @Override
    public void logic() {

        List<ArgsModel> argsModels = getArgsModels();
        if (argsModels.size()!=1 && !"messageCode".equals(argsModels.get(0).getName())) {
            Map<String, String> controll = InterfaceContext.logicControlContext.get();
            if (controll == null) {
                controll = new HashMap<>();
            }
            controll.put(InterfaceContext.CONTROLL_ERROR, "messageCode参数没有设置");
            return;
        }
        String messageCode = argsModels.get(0).getDefaultValue();

        System.out.println(Thread.currentThread().getName()+"---task---"+messageCode);

        Object data = getCurrentValue("data");
        if (data != null) {
            String dataStr = JSON.toJSONString(data);
            List<SubscribeModel> subscribeModels = subscribeDao.findAllByMessageCode(messageCode.toString());
            for (SubscribeModel subscribeModel : subscribeModels) {
                ThreadUtil.execute(new ExcuteMessage(dataStr,subscribeModel,messageCode));
            }
        }
        setResult("调用完成");
    }

    class ExcuteMessage extends Thread {
        private String dataStr;
        private SubscribeModel subscribeModel;
        private String messageCode;

        public ExcuteMessage(String dataStr, SubscribeModel subscribeModel,String messageCode) {
            this.dataStr = dataStr;
            this.subscribeModel = subscribeModel;
            this.messageCode = messageCode;
        }

        @Override
        public void run() {
            String s = subscribeModel.getmType();
            String url = subscribeModel.getUrl();
            String arg = subscribeModel.getArg();

            LogsModel logsModel = new LogsModel();
            logsModel.setName("任务调用");
            logsModel.setCode(messageCode);
            logsModel.setStartDate(new Date());
            logsModel.setUsersName(subscribeModel.getUsersName());
            logsModel.setUsersId(subscribeModel.getUsersId());


            if ("http".equalsIgnoreCase(s)) {
                HashMap<String, Object> argMap = new HashMap<>();
                argMap.put(arg, dataStr);
                for (int i = 0; i < 3; i++) {
                    try{
                        String post = HttpUtil.post(url, argMap, 5000);
                        //RequestBody方式调用
                        //String post = HttpRequest.post(url).body(JSON.toJSONString(argMap)).timeout(5000).execute().body();
                        HashMap hashMap = JSON.parseObject(post, HashMap.class);
                        if ("1".equals(hashMap.get("state"))) {
                            logsModel.setNote("发送成功");
                            break;
                        }
                    }catch (Exception e){
                        logsModel.setNote("发送失败");
                    }
                }
            } else if ("ws".equalsIgnoreCase(s)) {
                JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
                Client client = dcf.createClient(url);
                Object[] objects = new Object[0];
                for (int i = 0; i < 3; i++) {
                    try {
                        objects = client.invoke(arg, dataStr);
                        Object object = objects[0];
                        HashMap hashMap = JSON.parseObject(object.toString(), HashMap.class);
                        if ("1".equals(hashMap.get("state"))) {
                            logsModel.setNote("发送成功");
                            break;
                        }
                    } catch (Exception e) {
                        logsModel.setNote("发送失败");
                    }
                }
            }
            logsModel.setEndDate(new Date());
            logsService.save(logsModel);

        }

        public String getDataStr() {
            return dataStr;
        }

        public void setDataStr(String dataStr) {
            this.dataStr = dataStr;
        }

        public SubscribeModel getSubscribeModel() {
            return subscribeModel;
        }

        public void setSubscribeModel(SubscribeModel subscribeModel) {
            this.subscribeModel = subscribeModel;
        }
    }
}
